package com.itheima.ydd.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.ydd.common.CustomException;
import com.itheima.ydd.common.PageResult;
import com.itheima.ydd.common.Result;
import com.itheima.ydd.entity.*;
import com.itheima.ydd.service.*;
import com.itheima.ydd.utils.JwtUtils;
import com.itheima.ydd.vo.ChildrenConfigVo;
import com.itheima.ydd.vo.ConfigOneVo;
import com.itheima.ydd.vo.ConfigVo;
import com.itheima.ydd.vo.UserCateVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/index")
public class IndexUserController {

    @Autowired
    private YddArticleService yddArticleService;

    @Autowired
    private YddCateService yddCateService;

    @Autowired
    private YddUserService yddUserService;

    @Autowired
    private SysConfigService sysConfigService;

    @Autowired
    private YddTagService yddTagService;

    @Autowired
    private YddLinkService yddLinkService;

    @Autowired
    private YddAdvimgService yddAdvimgService;

    @GetMapping("/new")
    public Result newA(Long page,Long limit){
        Page<YddArticle> pageInfo = new Page<>(page,limit);
        Map map = new HashMap();
        map.put("desc","首页大列表");
        map.put("num_day",0);
        map.put("num_week",0);

        Long pageSize = limit;
        Long currentPage = page;
        LambdaQueryWrapper<YddArticle> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(YddArticle::getId);
        Page<YddArticle> page1 = yddArticleService.page(pageInfo, queryWrapper);
        //queryWrapper.last("limit 12");
        int count = yddArticleService.count(queryWrapper);
        List<YddArticle> list = page1.getRecords();
        List<UserCateVo> userCateVoList = list.stream().map(item -> {
            UserCateVo userCateVo = new UserCateVo();
            BeanUtils.copyProperties(item, userCateVo);
            Integer cateId = item.getCateid();
            if (cateId != null) {
                LambdaQueryWrapper<YddCate> ycQueryWrapper = new LambdaQueryWrapper<>();
                ycQueryWrapper.eq(YddCate::getId, cateId);
                YddCate one = yddCateService.getOne(ycQueryWrapper);
                userCateVo.setCatename(one.getCatename());
            }
            return userCateVo;
        }).collect(Collectors.toList());
        PageResult answer = PageResult.answer((long) count, pageSize, currentPage, userCateVoList);
        map.put("list",answer);

        return Result.ok("新文章",map);
    }

    @GetMapping("/list")
    public Result list(Long page, Long limit, Integer cateid){
        Page<YddArticle> pageInfo = new Page<>(page,limit);
        Map map = new HashMap();
        Long currentPage = page;
        Long pageSize = limit;
        LambdaQueryWrapper<YddArticle> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(YddArticle::getCateid,cateid);
        Page<YddArticle> page1 = yddArticleService.page(pageInfo, queryWrapper);
        List<YddArticle> yddArticleList = page1.getRecords();
        int count = yddArticleService.count(queryWrapper);
        List<UserCateVo> collect = yddArticleList.stream().map(item -> {
            UserCateVo userCateVo = new UserCateVo();
            BeanUtils.copyProperties(item, userCateVo);
            Integer cateId = item.getCateid();
            if (cateId != null) {
                LambdaQueryWrapper<YddCate> ycQueryWrapper = new LambdaQueryWrapper<>();
                ycQueryWrapper.eq(YddCate::getId, cateId);
                YddCate one = yddCateService.getOne(ycQueryWrapper);
                userCateVo.setCatename(one.getCatename());
            }
            return userCateVo;
        }).collect(Collectors.toList());
        PageResult answer = PageResult.answer((long) count, pageSize, currentPage, collect);
        map.put("list",answer);
        return Result.ok("分类文章",map);
    }

    @PostMapping("/reg")
    public Result register(@RequestBody YddUser yddUser){
        Map map = new HashMap();
        LambdaQueryWrapper<YddUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(YddUser::getMobile,yddUser.getMobile());
        int count = yddUserService.count(queryWrapper);
        if (count != 0){
            throw new CustomException("该用户已存在，请勿重复注册");
        }
        //将用户信息存入数据库
        YddUser yddUser1 = new YddUser();
        yddUser1.setMobile(yddUser.getMobile());
        yddUser1.setPassword(DigestUtils.md5DigestAsHex(yddUser.getPassword().getBytes()));
        yddUser1.setUsername(yddUser.getMobile());
        yddUserService.save(yddUser1);
        //获取刚刚注册的用户的id
        LambdaQueryWrapper<YddUser> yuQueryWrapper = new LambdaQueryWrapper<>();
        yuQueryWrapper.eq(YddUser::getMobile,yddUser.getMobile());
        YddUser one = yddUserService.getOne(queryWrapper);
        //通过JWT生成token
        Map tokenMap = new HashMap();
        tokenMap.put("id",one.getId());
        tokenMap.put("mobile",one.getMobile());
        String token = JwtUtils.getToken(tokenMap);
        map.put("token",token);
        return Result.ok("注册",map);

    }

    @GetMapping("/hot")
    public Result hot(){
        Map map = new HashMap();
        map.put("desc","侧边最新文章");
        //热点文章查询条件
        LambdaQueryWrapper<YddArticle> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(YddArticle::getClick);
        queryWrapper.last("limit 6");
        List<YddArticle> list = yddArticleService.list(queryWrapper);
        List<UserCateVo> userCateVoList = list.stream().map(item -> {
            UserCateVo userCateVo = new UserCateVo();
            BeanUtils.copyProperties(item, userCateVo);
            Integer cateid = item.getCateid();
            if (cateid != null) {
                LambdaQueryWrapper<YddCate> ycqueryWrapper = new LambdaQueryWrapper<>();
                ycqueryWrapper.eq(YddCate::getId, cateid);
                YddCate one = yddCateService.getOne(ycqueryWrapper);
                userCateVo.setCatename(one.getCatename());
            }
            return userCateVo;
        }).collect(Collectors.toList());
        map.put("list",userCateVoList);
        return Result.ok("热点文章",map);
    }

    @GetMapping("/recommend")
    public Result recommend(){
        Map map = new HashMap();
        map.put("desc","侧边最新文章");
        //热点文章查询条件
        LambdaQueryWrapper<YddArticle> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(YddArticle::getClick);
        queryWrapper.last("limit 6");
        List<YddArticle> list = yddArticleService.list(queryWrapper);
        List<UserCateVo> userCateVoList = list.stream().map(item -> {
            UserCateVo userCateVo = new UserCateVo();
            BeanUtils.copyProperties(item, userCateVo);
            Integer cateid = item.getCateid();
            if (cateid != null) {
                LambdaQueryWrapper<YddCate> ycqueryWrapper = new LambdaQueryWrapper<>();
                ycqueryWrapper.eq(YddCate::getId, cateid);
                YddCate one = yddCateService.getOne(ycqueryWrapper);
                userCateVo.setCatename(one.getCatename());
            }
            return userCateVo;
        }).collect(Collectors.toList());
        map.put("list",userCateVoList);
        return Result.ok("推荐文章",map);
    }

    @GetMapping("/index")
    public Result index(){
        Map map = new HashMap();
        ConfigOneVo configOneVo = new ConfigOneVo();
        List<ConfigVo> list = new ArrayList<>();
        map.put("allCate",yddCateService.list());
        //base 基础配置 system 系统配置 custom 其他配置
        //获得所有配置对应kv
        Map<String, Set<String>> configMap = new HashMap<>();
        configMap.put("base",getGroupValue("base"));
        configMap.put("system",getGroupValue("system"));
        configMap.put("custom",getGroupValue("custom"));
        Set<String> set = configMap.keySet();
        for (String s : set) {
            if(s.equals("base")){
                ConfigVo configVo = new ConfigVo();
                Set<String> name = configMap.get(s);
                configVo.setKey(s);
                configVo.setName("基础配置");
                List<ChildrenConfigVo> ccvList = new ArrayList<>();
                for (String n : name) {
                    ChildrenConfigVo ccv = new ChildrenConfigVo();
                    ccv.setName(n);
                    LambdaQueryWrapper<SysConfig> queryWrapper = new LambdaQueryWrapper<>();
                    queryWrapper.eq(SysConfig::getGroup_value,n);
                    List<SysConfig> scList = sysConfigService.list(queryWrapper);
                    ccv.setData(scList);
                    ccvList.add(ccv);
                }
                configVo.setChildren(ccvList);
                list.add(configVo);
            }
            /////
            if(s.equals("system")){
                ConfigVo configVo = new ConfigVo();
                Set<String> name = configMap.get(s);
                configVo.setKey(s);
                configVo.setName("系统设置");
                List<ChildrenConfigVo> ccvList = new ArrayList<>();
                for (String n : name) {
                    ChildrenConfigVo ccv = new ChildrenConfigVo();
                    ccv.setName(n);
                    LambdaQueryWrapper<SysConfig> queryWrapper = new LambdaQueryWrapper<>();
                    queryWrapper.eq(SysConfig::getGroup_value,n);
                    List<SysConfig> scList = sysConfigService.list(queryWrapper);
                    ccv.setData(scList);
                    ccvList.add(ccv);
                }
                configVo.setChildren(ccvList);
                list.add(configVo);
            }
            ///
            if(s.equals("custom")){
                ConfigVo configVo = new ConfigVo();
                Set<String> name = configMap.get(s);
                configVo.setKey(s);
                configVo.setName("其他配置");
                List<ChildrenConfigVo> ccvList = new ArrayList<>();
                for (String n : name) {
                    ChildrenConfigVo ccv = new ChildrenConfigVo();
                    ccv.setName(n);
                    LambdaQueryWrapper<SysConfig> queryWrapper = new LambdaQueryWrapper<>();
                    queryWrapper.eq(SysConfig::getGroup_value,n);
                    List<SysConfig> scList = sysConfigService.list(queryWrapper);
                    ccv.setData(scList);
                    ccvList.add(ccv);
                }
                configVo.setChildren(ccvList);
                list.add(configVo);
            }
        }
        configOneVo.setList(list);
        map.put("config",configOneVo);
        //获取所有配置
        map.put("allData",sysConfigService.list());
        //获得所有标签
        map.put("allTag",yddTagService.list());
        //获得所有链接
        map.put("allLink",yddLinkService.list());
        //获取广告图片链接
        map.put("banner",yddAdvimgService.list());
        //side链接
        map.put("sideBanner",yddAdvimgService.list(new LambdaQueryWrapper<YddAdvimg>().last("limit 4")));
        //show链接
        map.put("showBanner",yddAdvimgService.list(new LambdaQueryWrapper<YddAdvimg>().last("limit 2")));
        return Result.ok("首页",map);
    }

    //获得配置分组
    private Set<String> getGroupValue(String config) {
        Set<String> set = new HashSet<>();
        LambdaQueryWrapper<SysConfig> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysConfig::getTab_value,config);
        List<SysConfig> list = sysConfigService.list(queryWrapper);
        for (SysConfig sysConfig : list) {
            set.add(sysConfig.getGroup_value());
        }
        return set;
    }
}
